rem New Problem Wizard

name = ""
If WScript.Arguments.Count = 1 Then
	name = WScript.Arguments(0)
Else
	If WScript.Arguments.Count = 0 Then
		name = InputBox("enter problem name")
	End If
End If

If name = "" Then
	Wscript.Echo "Usage: wizard.vbs ProblemName"
	WScript.Quit(1)
End If

Set re = New RegExp
re.Pattern    = "^[a-zA-Z_][a-zA-Z0-9_]*$"
re.IgnoreCase = False
re.Global     = False

If Not re.Test(name) Then
	Wscript.Echo "ERROR: bad ProblemName"
	WScript.Quit(1)
End If

cap_name=UCase(Mid(name, 1, 1)) + Mid(name, 2)
up_name=UCase(name)
lo_name=LCase(name)

Set fso = CreateObject("Scripting.FileSystemObject")

new_dir = ".\" + lo_name
gen_dir = ".\generic"
problems_dir = "..\problems\" + lo_name

If fso.FolderExists(new_dir) Then
	Wscript.Echo "ERROR: folder '" + lo_name + "' already exist"
	WScript.Quit(1)
End If

If Not fso.FolderExists(gen_dir) Then
	Wscript.Echo "ERROR: 'generic' folder not found"
	WScript.Quit(1)
End If

Function get_ext(ByRef fname)
	Dim ext
	ext = Split(fname,".")
	If (UBound(ext) = 1) Then
		get_ext = ext(1)
	Else
		get_ext = ""
	End If
End Function

Function read_file(fname)
	Dim stream
	Set stream = fso.OpenTextFile(fname)
	read_file = stream.ReadAll
End Function

Function write_file(fname, text)
	Dim stream
	Set stream = fso.OpenTextFile(fname, 2, True, 0)
	stream.Write text
End Function

Sub do_recursive(ByRef dir, ByVal new_path)
	Dim text, new_text
	Set newfolder = fso.CreateFolder(new_path)
	For Each f in dir.Files
		rem Wscript.Echo f.Path
		rem Wscript.Echo get_ext(f.Name)
		ext = get_ext(f.Name)
		If ext = "h" Or ext = "cpp" Or ext = "ini" Or ext = "sh" Or ext = "cmd" Or ext = "vcproj" Or f.Name = "Makefile" Then
			new_name = new_path + "\" + Replace(f.Name, "generic", lo_name)
			text = read_file(f.Path)
			new_text = Replace(text, "generic", lo_name)
			new_text = Replace(new_text, "Generic", cap_name)
			new_text = Replace(new_text, "GENERIC", up_name)
			write_file new_name, new_text
		End If
	Next
	For Each d in dir.SubFolders
		If Not d.Attributes And 2 Then
			If d.Name <> ".svn" And d.Name <> "_svn" Then
	        		rem Wscript.Echo d.Path
				sub_path = new_path + "\" + d.Name
	        		do_recursive d, sub_path
			End If
		End If
        Next
End Sub

If Not fso.FolderExists(problems_dir) Then
	Set prfolder = fso.CreateFolder(problems_dir)
Else
	Set prfolder = fso.GetFolder(problems_dir)
End If

do_recursive fso.GetFolder(gen_dir), new_dir

Wscript.Echo "Project '" + name +"' created successfully." + vbNewLine + "Please copy problem instances to '" + prfolder.Path + "'"

rem eof
